package com.zm.demo.netty.server.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author z01140
 * @Package: com.zm.demo.netty.server.http
 * @Description:
 * @CreateDate 2023/8/31 10:01
 * @UpdateDate 2023/8/31 10:01
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    HttpRequest request;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest){
            request = (HttpRequest) msg;
            HttpMethod method = request.method();
            String uri = request.uri();
            System.out.println("uri=" + uri + ", method=" + method.name());
        }
        if (msg instanceof HttpContent){
            HttpContent content = (HttpContent) msg;
            ByteBuf byteBuf = content.content();
            System.out.println("request_content=" + byteBuf.toString(io.netty.util.CharsetUtil.UTF_8));

            ByteBuf byteBuf1 = Unpooled.copiedBuffer("response :" + byteBuf.toString(io.netty.util.CharsetUtil.UTF_8) , CharsetUtil.UTF_8);

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf1);
            response.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf8");
            response.headers().add(HttpHeaderNames.CONTENT_LENGTH, byteBuf1.readableBytes());
            ctx.writeAndFlush(response);
        }
    }
}
